package com.china.produce.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.china.produce.constat.SecurityConstants;
import com.china.produce.context.SecurityContextHolder;
import com.china.produce.system.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/3/3
 */
@Component
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(HeaderInterceptor.class);

    @Autowired
    private RedisUtil redisUtil;

    private static final String TOKEN_KEY = "token";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = StringUtils.defaultIfBlank(request.getHeader(TOKEN_KEY), request.getParameter(TOKEN_KEY));
        String sUser = redisUtil.get("access_token" + token);
        LOG.info("token: {}", token);
        if (!StrUtil.isEmpty(sUser)) {

            SecurityContextHolder.set(SecurityConstants.USER_KEY, sUser);
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        LOG.info("post Handle .....");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        SecurityContextHolder.remove();

        System.out.println("after completion .....");
    }
}
